import axios from 'axios';
import { getRedirectPath } from '../util'
//定义动作类型

const AUTH_SUCCESS = 'AUTH_SUCCESS';
const ERROR_MSG = 'ERROR_MSG';
const LOAD_DATA = 'LOAD_DATA';
const LOGOUT = 'LOGOUT';

//用户初始状态
const initState = {
	redirectTo:null,
	msg:'',
	user:'',
	type:''
}

//reducer
export function user(state = initState,action){
	switch (action.type){
		case AUTH_SUCCESS:
			return {...state,redirectTo:getRedirectPath(action.payload),...action.payload}
		case LOAD_DATA:
			return {...state,...action.payload}
		case ERROR_MSG:
			return {...state,msg:action.msg}
		case LOGOUT:
			return {...initState,redirectTo:'/login'}
		default:
			break;
	}
	
	return state;
}

function errorMsg(msg){
	return {msg,type:ERROR_MSG};
}
function authSuccess(data){
	return {payload:data,type:AUTH_SUCCESS};
}
function loadDataSuccess(data){
	return{type:LOAD_DATA,payload:data};

}

export function logout(){
	return {type:LOGOUT}
}

//进行的动作
export function update(data){
	return dispatch =>{
		axios.post('/user/update',data)
			.then(res =>{
				if (res.status === 200) {
					if (res.data.code === 0) {
						dispatch(authSuccess(res.data.content));
					} else{
						dispatch(errorMsg(res.data.msg));
					}
				} else{
					dispatch(errorMsg('服务器响应失败'));
				}
			});
	} 
}

export function loadData(){
	return async(dispatch) =>{
		const res = await axios.get('/user/info');
		if (res.status === 200) {
			if (res.data.code === 0) {
				dispatch(loadDataSuccess(res.data.content));
			} else{
				dispatch(errorMsg(res.data.msg));
			}
		} else{
			dispatch(errorMsg('服务器响应失败'));
		}					
	} 
}
export function register({user,pwd,repeatpwd,type}){
	if(!user || !pwd || !type){
		return errorMsg('用户名密码不能为空');
	}
	
	if (pwd !== repeatpwd) {
		return errorMsg('前后密码不一致');
	}
	
	return  dispatch =>{
		axios.post('/user/register',{user,pwd,type})
			.then(res => {
				if (res.status === 200) {
					if (res.data.code === 0) {
						dispatch(authSuccess(res.data.content));
					} else{
						dispatch(errorMsg(res.data.msg));
					}
				} else{
					dispatch(errorMsg('服务器响应失败'));
				}
			})
	}
}

export function login({user,pwd}){
	if (!user || !pwd ) {
		return errorMsg('用户名密码不能为空');
	}
	
	return dispatch =>{
		axios.post('/user/login',{user,pwd})
			.then(res =>{
				if (res.status === 200) {
					if (res.data.code === 0) {
						dispatch(authSuccess(res.data.content));
					} else{
						dispatch(errorMsg(res.data.msg));
					}
				} else{
					dispatch(errorMsg('服务器响应失败'));
				}
			});
	}
}